<template>
  <div class="timeline-editor">
    <div class="timeline-header">
      <div class="project-info" v-if="project">
        Project: {{ project.name }}
      </div>
      <div class="timeline-controls">
        <button @click="playPause" :disabled="!timeline || !timeline.tracks?.length" class="control-button">
          {{ isPlaying ? 'Pause' : 'Play' }}
        </button>
        <button @click="stop" :disabled="!timeline" class="control-button">
          Stop
        </button>
        <button @click="addTrack" :disabled="!timeline" class="control-button">
          Add Track
        </button>
      </div>
    </div>
    
    <div v-if="timeline" class="timeline-content">
      <div class="track-list">
        <div class="track-list-header">
          <h3>Tracks</h3>
        </div>
        
        <div 
          v-for="track in (timeline.tracks || [])" 
          :key="track.id"
          class="track-item"
          :class="{ active: selectedTrack === track.id }"
          @click="selectTrack(track.id)"
        >
          <div class="track-header">
            <span class="track-name">{{ track.name }}</span>
            <span class="track-type">{{ track.type }}</span>
          </div>
          <div class="track-keyframes-count">
            {{ track.keyframes ? track.keyframes.length : 0 }} keyframes
          </div>
        </div>
        
        <div v-if="!(timeline.tracks && timeline.tracks.length)" class="no-tracks">
          No tracks available. Add tracks to start editing.
        </div>
      </div>
      
      <div class="keyframe-view">
        <div class="timeline-ruler">
          <div 
            v-for="tick in timeRulerTicks" 
            :key="tick.time"
            class="time-tick"
            :style="{ left: `${tick.position}%` }"
          >
            <span class="time-label">{{ tick.label }}</span>
          </div>
        </div>
        
        <div class="tracks-container">
          <div 
            v-for="track in (timeline.tracks || [])" 
            :key="track.id"
            class="track-row"
            :class="{ active: selectedTrack === track.id }"
            @click="selectTrack(track.id)"
          >
            <div 
              v-for="keyframe in (track.keyframes || [])" 
              :key="keyframe.id"
              class="keyframe"
              :class="{ selected: selectedKeyframes.includes(keyframe.id) }"
              :style="{ left: `${(keyframe.time / totalTime) * 100}%` }"
              @click.stop="toggleKeyframeSelection(keyframe.id)"
            >
            </div>
          </div>
        </div>
        
        <div class="playhead" :style="{ left: `${(currentTime / totalTime) * 100}%` }"></div>
      </div>
    </div>
    
    <div v-else class="loading">
      Loading timeline...
    </div>
    
    <div v-if="timeline" class="timeline-footer">
      <div class="time-display">
        {{ formatTime(currentTime) }} / {{ formatTime(totalTime) }}
      </div>
      
      <div class="track-actions">
        <button @click="addKeyframe" :disabled="!selectedTrack" class="control-button">
          Add Keyframe
        </button>
        <button @click="deleteSelectedKeyframes" :disabled="!selectedKeyframes.length" class="control-button delete-button">
          Delete Keyframes
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import apiService from '../../services/api.js';

export default {
  name: 'TimelineEditor',
  props: {
    projectId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      project: null,
      timeline: null,
      currentTime: 0,
      totalTime: 300, // 5 minutes default
      isPlaying: false,
      selectedTrack: null,
      selectedKeyframes: [],
      playInterval: null
    };
  },
  computed: {
    timeRulerTicks() {
      const ticks = [];
      const interval = 30; // seconds per tick
      
      if (!this.timeline || !this.totalTime) return ticks;
      
      for (let time = 0; time <= this.totalTime; time += interval) {
        ticks.push({
          time: time,
          position: (time / this.totalTime) * 100,
          label: this.formatTime(time)
        });
      }
      
      return ticks;
    },
    
    playheadPosition() {
      return (this.currentTime / this.totalTime) * 100;
    }
  },
  mounted() {
    this.loadProject();
    this.loadTimeline();
  },
  beforeUnmount() {
    if (this.playInterval) {
      clearInterval(this.playInterval);
    }
  },
  methods: {
    async loadProject() {
      try {
        this.project = await apiService.getProject(this.projectId);
        console.log(`Loaded project: ${this.project.name}`);
      } catch (error) {
        console.error('Failed to load project:', error);
      }
    },
    
    async loadTimeline() {
      try {
        const response = await apiService.getTimeline(this.projectId);
        const timelineData = response.data || response;
        this.timeline = timelineData;
        this.totalTime = timelineData.duration || 300;
        console.log('Loaded timeline data');
      } catch (error) {
        console.error('Failed to load timeline:', error);
        this.timeline = { tracks: [] }; // 设置默认空timeline
      }
    },
    
    async updateTimeline() {
      if (!this.timeline) return;
      
      try {
        await apiService.updateTimeline(this.timeline.id, this.timeline);
        console.log('Timeline updated successfully');
      } catch (error) {
        console.error('Failed to update timeline:', error);
      }
    },
    
    selectTrack(trackId) {
      this.selectedTrack = trackId;
    },
    
    toggleKeyframeSelection(keyframeId) {
      const index = this.selectedKeyframes.indexOf(keyframeId);
      if (index >= 0) {
        this.selectedKeyframes.splice(index, 1);
      } else {
        this.selectedKeyframes.push(keyframeId);
      }
    },
    
    playPause() {
      if (this.isPlaying) {
        this.pause();
      } else {
        this.play();
      }
    },
    
    play() {
      if (!this.timeline || !this.timeline.tracks?.length) return;
      
      this.isPlaying = true;
      
      // Animate playhead
      this.playInterval = setInterval(() => {
        this.currentTime += 0.1; // Increment by 0.1 seconds
        
        if (this.currentTime >= this.totalTime) {
          this.currentTime = 0;
          this.pause();
        }
      }, 100);
      
      console.log('Playback started');
    },
    
    pause() {
      this.isPlaying = false;
      if (this.playInterval) {
        clearInterval(this.playInterval);
        this.playInterval = null;
      }
      console.log('Playback paused');
    },
    
    stop() {
      this.isPlaying = false;
      this.currentTime = 0;
      
      if (this.playInterval) {
        clearInterval(this.playInterval);
        this.playInterval = null;
      }
      
      console.log('Playback stopped');
    },
    
    async addTrack() {
      const trackName = prompt('Enter track name:');
      if (!trackName) return;
      
      const trackType = prompt('Enter track type (dialogue/animation/camera/audio):', 'animation');
      if (!trackType) return;
      
      const newTrack = {
        id: Date.now().toString(),
        name: trackName,
        type: trackType,
        keyframes: []
      };
      
      this.timeline.tracks.push(newTrack);
      await this.updateTimeline();
    },
    
    async addKeyframe() {
      if (!this.selectedTrack) {
        alert('Please select a track first');
        return;
      }
      
      try {
        const keyframeData = {
          trackId: this.selectedTrack,
          time: this.currentTime,
          properties: {}
        };
        
        const newKeyframe = await apiService.addKeyframe(keyframeData);
        console.log('Added new keyframe:', newKeyframe);
        
        // Update local timeline data
        const track = this.timeline.tracks.find(t => t.id === this.selectedTrack);
        if (track) {
          if (!track.keyframes) {
            track.keyframes = [];
          }
          track.keyframes.push(newKeyframe);
        }
        
        // Select the new keyframe
        this.selectedKeyframes = [newKeyframe.id];
      } catch (error) {
        console.error('Failed to add keyframe:', error);
      }
    },
    
    async deleteSelectedKeyframes() {
      if (!this.selectedKeyframes.length) return;
      
      if (!confirm(`Are you sure you want to delete ${this.selectedKeyframes.length} keyframe(s)?`)) {
        return;
      }
      
      try {
        // Delete each selected keyframe
        for (const keyframeId of this.selectedKeyframes) {
          await apiService.deleteKeyframe(keyframeId);
          
          // Update local timeline data
          for (const track of this.timeline.tracks) {
            if (track.keyframes) {
              const index = track.keyframes.findIndex(kf => kf.id === keyframeId);
              if (index >= 0) {
                track.keyframes.splice(index, 1);
                break;
              }
            }
          }
        }
        
        console.log(`Deleted ${this.selectedKeyframes.length} keyframes`);
        this.selectedKeyframes = [];
      } catch (error) {
        console.error('Failed to delete keyframes:', error);
        alert('Failed to delete some keyframes. Please try again.');
      }
    },
    
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
  }
};
</script>

<style scoped>
.timeline-editor {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.timeline-header {
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.project-info {
  font-size: 14px;
  color: #666;
}

.timeline-controls {
  display: flex;
  gap: 10px;
}

.timeline-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.track-list {
  width: 250px;
  border-right: 1px solid #eee;
  overflow-y: auto;
  background-color: #fafafa;
}

.track-list-header {
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
  background-color: #f8f9fa;
  font-weight: bold;
  color: #333;
}

.track-item {
  padding: 12px 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.track-item:hover {
  background-color: #e9ecef;
}

.track-item.active {
  background-color: #007bff;
  color: white;
}

.track-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.track-name {
  font-weight: bold;
}

.track-type {
  font-size: 12px;
  background-color: #6c757d;
  color: white;
  padding: 2px 6px;
  border-radius: 10px;
}

.track-keyframes-count {
  font-size: 12px;
  color: #6c757d;
}

.no-tracks {
  padding: 20px;
  text-align: center;
  color: #6c757d;
  font-style: italic;
}

.loading {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  color: #6c757d;
  font-style: italic;
}

.keyframe-view {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
  position: relative;
}

.timeline-ruler {
  height: 30px;
  border-bottom: 1px solid #ddd;
  background-color: #f8f9fa;
  position: relative;
}

.time-tick {
  position: absolute;
  top: 0;
  height: 100%;
  display: flex;
  align-items: center;
}

.time-tick::before {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  width: 1px;
  background-color: #ccc;
}

.time-label {
  position: absolute;
  top: 5px;
  left: 5px;
  font-size: 11px;
  color: #666;
}

.tracks-container {
  flex: 1;
  position: relative;
}

.track-row {
  height: 50px;
  border-bottom: 1px solid #eee;
  position: relative;
  background-color: #fff;
}

.track-row:hover {
  background-color: #f8f9fa;
}

.track-row.active {
  background-color: #e3f2fd;
}

.keyframe {
  position: absolute;
  width: 12px;
  height: 12px;
  background-color: #007bff;
  border: 2px solid #fff;
  border-radius: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  cursor: pointer;
  box-shadow: 0 1px 3px rgba(0,0,0,0.3);
  z-index: 2;
}

.keyframe:hover {
  background-color: #0056b3;
  transform: translate(-50%, -50%) scale(1.2);
}

.keyframe.selected {
  background-color: #ffc107;
  border-color: #fff;
}

.playhead {
  position: absolute;
  top: 30px; /* Account for ruler height */
  bottom: 0;
  width: 2px;
  background-color: #dc3545;
  z-index: 3;
  pointer-events: none;
}

.playhead::before {
  content: '';
  position: absolute;
  top: -10px;
  left: -5px;
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 10px solid #dc3545;
}

.timeline-footer {
  padding: 10px 15px;
  border-top: 1px solid #eee;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.control-button {
  padding: 8px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.control-button:hover {
  background-color: #0056b3;
}

.control-button:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.delete-button {
  background-color: #dc3545;
}

.delete-button:hover {
  background-color: #c82333;
}

.delete-button:disabled {
  background-color: #6c757d;
}

.time-display {
  font-family: monospace;
  font-size: 14px;
  min-width: 100px;
  text-align: center;
}

.track-actions {
  display: flex;
  gap: 10px;
}
</style>